#!/bin/bash
# enable/disable cool-n'-quiet (in this case cpu scaling-governor and Throtteling state)
# you can use (among others) xbindkeys to attack this Script to a specific Keycode
# Written by: info2 (http://ubuntuforums.org/showpost.php?p=2729423&postcount=2)
#
for CPU in /sys/devices/system/cpu/*; do
    if test -d $CPU; then
	if test $(cat $CPU/cpufreq/scaling_governor) == "ondemand"; then
      		echo -n "conservative" > $CPU/cpufreq/scaling_governor

		#get the minimal sampling rate and append a "0" (= same like multiplication with 10)
		SAMPLINGRATE=$(cat $CPU/cpufreq/conservative/sampling_rate_min)0
		
		#test if our samplingrate is greater than the systems maximum sampling rate
		#the systems sampling_rate_max often is too big and causes the cpu running 
		#long time at a higher frequency before the governor switches back.
		#a too small sampling rate wakes up the processor too much often by governor

		if [ $SAMPLINGRATE -gt $(cat $CPU/cpufreq/conservative/sampling_rate_max) ] 
		then
		    SAMPLINGRATE=$(cat $CPU/cpufreq/conservative/sampling_rate_max)
		fi

		echo -n $SAMPLINGRATE > $CPU/cpufreq/conservative/sampling_rate

		#setting a user-limit throttling-state
		#4 is 50% on my system.
		#look at cat /proc/acpi/processor/CPU?/throttling for more values
		for ACPICPU in /proc/acpi/processor/*; do
			echo -n "0:4" > $ACPICPU/limit
		done
		MESSAGE="Activated"
	else
      		echo -n "ondemand" > $CPU/cpufreq/scaling_governor
		cat $CPU/cpufreq/ondemand/sampling_rate_min > $CPU/cpufreq/ondemand/sampling_rate

		#setting user-limit throttling-state to 0 (=no throttling)
		for ACPICPU in /proc/acpi/processor/*; do
			echo -n "0:0" > $ACPICPU/limit
		done
		MESSAGE="Deactivated"
	fi
   fi
done
#send Notification to the user that called this script
notify-send --urgency="normal" --expire-time=5000 --icon="gtk-info" "Cool'n'Quiet" $MESSAGE

